<!DOCTYPE html>
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>


    <link media="all" rel="stylesheet" th:href="@{/layui/css/layui.css}"/>
    <link media="all" rel="stylesheet" th:href="@{/css/public.css}"/>
    <link media="all" rel="stylesheet" th:href="@{/layui_ext/dtree/dtree.css}"/>
    <link media="all" rel="stylesheet" th:href="@{/layui_ext/dtree/font/dtreefont.css}"/>
    <style>
        input#search_deptTree_select_input_id {
            border-radius: 10px;
            height: 30px;
            margin-top: 4px;
        }

        input#deptTree_select_input_id {
            border-radius: 10px;
            height: 30px;
            margin-top: 4px;
        }

        input#leaderdeptTree_select_input_id {
            border-radius: 10px;
            height: 30px;
            margin-top: 4px;
        }

        input.layui-input.layui-unselect {
            border-radius: 10px;
            height: 30px;
            margin-top: 4px;
        }

        /* 调整日期范围选择器的样式 */
        .layui-input-inline {
            width: 150px;
        }

        /* 定义表格父容器的样式，使其成为弹性布局容器，并将子元素居中 */
        .table-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 50px; /* 可根据需要调整表格与上方搜索框的间距 */
        }

        .table-container-search{
            margin-right: 20px; /* 可根据需要调整搜索框与表格的间距 */
            margin-left: 50px;
            padding-top: 15px;
            margin-bottom: -20px;
        }

        /* 设置表格行高  新增：垂直居中 */
        .layui-table-cell {
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
            height: 48px !important;
            line-height: normal !important; /* 重置行高 */
            text-align: center !important;
        }

        /* 修正头像垂直对齐（关键修改） */
        .userAvatar {
            display: block !important;
            margin: 0 auto !important;
            vertical-align: middle !important;
            max-height: 40px !important;
            max-width: 40px !important;
        }
    </style>
</head>
<body>
<div class="table-container-search">
    <!--查询条件-->
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 15px;">
        <legend>搜索条件</legend>
    </fieldset>
    <form action="" class="layui-form" id="searchFrm" lay-filter="searchFrm" method="post">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-inline">
                    <input class="layui-input input-radius" id="username" name="username" placeholder="请输入用户名" type="text">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">手机号</label>
                <div class="layui-input-inline">
                    <input class="layui-input input-radius" name="phone" placeholder="请输入用户手机号"
                           type="text">
                </div>
            </div>
            <div class="layui-inline" style="text-align: center;padding-right: 15%;padding-left: 40px">
                <button class="layui-btn layui-btn-sm layui-btn-radius" lay-filter="doSearch" lay-submit="" type="button"><i
                        class="layui-icon layui-icon-search layui-icon-normal"></i>查询
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm"
                        onclick="javascript:document.getElementById('search_deptid').value=''"
                        type="reset"><i
                        class="layui-icon layui-icon-refresh"></i><span>重置</span>
                </button>
            </div>
        </div>
    </form>
</div>

<!--数据表格-->
<div class="table-container">
    <table class="layui-hide layui-table-cell" id="userTable" lay-filter="userTable"></table>
    <div id="userToolBar" style="display: none">
        <button class="layui-btn layui-btn-sm layui-btn-normal layui-btn-radius" lay-event="add" type="button">
            <i class="layui-icon layui-icon-add-1"></i>添加用户
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius" lay-event="batchDelete" type="button">
            <i class="layui-icon layui-icon-delete"></i>批量删除
        </button>
    </div>
    <div id="userRowBar" style="display: none;">
        <button class="layui-btn layui-btn-xs layui-btn-radius" lay-event="update" type="button"><i
                class="layui-icon layui-icon-edit"></i>编辑
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-danger layui-btn-radius" lay-event="delete" type="button"><i
                class="layui-icon layui-icon-delete"></i>删除
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-warm layui-btn-radius" lay-event="resetPwd" type="button"><i
                class="layui-icon layui-icon-refresh-3"></i>重置密码
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-normal layui-btn-radius" lay-event="updateAvatar" type="button"><i
                class="layui-icon layui-icon-delete"></i>更换头像
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-danger layui-btn-radius" lay-event="selectRole" type="button"><i
                class="layui-icon layui-icon-delete"></i>分配角色
        </button>
    </div>
</div>

<!--添加和修改弹出层-->
<div id="addOrUpdateDiv" style="display: none;padding: 10px;padding-right: 5%">
    <form action="" class="layui-form" id="dataFrm" lay-verify="required" lay-filter="dataFrm" method="post">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户名：</label>
                <div class="layui-input-block">
                    <input name="id" type="hidden">
                    <input autocomplete="off" class="layui-input input-radius" lay-verify="required" name="username"
                           placeholder="请输入用户名" type="text">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">登陆密码：</label>
                <div class="layui-input-block">
                    <input autocomplete="off" class="layui-input input-radius" id="loginname" lay-verify="required"
                           name="password"
                           placeholder="请输入登陆密码" type="text">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">姓名：</label>
                <div class="layui-input-block">
                    <input class="layui-input input-radius" id="name" name="name" placeholder="请输入用户姓名"
                           type="text">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">年龄：</label>
                <div class="layui-input-block">
                    <input class="layui-input input-radius" id="age" name="age" placeholder="请输入用户年龄" type="text">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">手机号：</label>
                <div class="layui-input-block">
                    <input class="layui-input input-radius" id="phone" name="phone" placeholder="请输入用户手机号">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">身份证：</label>
                <div class="layui-input-block">
                    <input class="layui-input input-radius" id="idCard" name="idCard" placeholder="请输入用户身份证">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户性别：</label>
                <div class="layui-input-block">
                    <input checked="" name="sex" title="男" type="radio" value="1">
                    <input name="sex" title="女" type="radio" value="0">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户住址：</label>
                <div class="layui-input-block">
                    <input class="layui-input input-radius" id="address" name="address" placeholder="请输入用户住址"
                           type="text">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;padding-right: 7%">
                <button class="layui-btn layui-btn-radius" id="doSubmit" lay-filter="doSubmit" lay-submit=""
                        type="button"><i
                        class="layui-icon layui-icon-search layui-icon-normal"></i>提交
                </button>
                <button class="layui-btn layui-btn-radius layui-btn-warm"
                        onclick="javascript:document.getElementById('deptid').value=''"
                        type="reset"><i
                        class="layui-icon layui-icon-refresh"></i><span>重置</span>
                </button>
            </div>
        </div>
    </form>
</div>

<!--给用户分配角色的弹出层-->
<div id="selectUserRoleDiv" style="display: none;padding: 10px;">
    <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
</div>



<!-- 要记得检查路径是否正确 -->
<script th:src="@{/layui/layui.js}" type="text/javascript"></script>

<script type="text/javascript">

    //提升数据表格的作用域，因为底下还有一个reloadTable方法
    var tableIns;

    layui.extend({
        dtree: '/layui_ext/dtree/dtree'
    }).use(['jquery', 'form', 'layer', 'table', 'dtree', 'laydate'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;
        var table = layui.table;
        var dtree = layui.dtree;
        var laydate = layui.laydate;

        //初始化时间选择器
        laydate.render({
            elem: "#hiredate",
            type: "datetime"
        });

        //初始化表格 加载数据
        tableIns = table.render({
            elem: "#userTable",
            title: "用户数据表格",
            url: "/user/loadAllUser",
            toolbar: "#userToolBar",
            page: true,
            width: 1500,
            height: "full-180",

            cols: [ [
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: 'ID', align: 'center', width: '50',hide: true},
                {field: 'username', title: '用户名', align: 'center', width: '120'},
                {field: 'password', title: '密码', align: 'center', width: '130'},
                {field: 'imgPath', title: '头像', align: 'center', width: '70', // 修正代码（添加协议头和空值处理）
                    templet: function (d) {
                        // 获取头像路径，如果为空则使用默认头像路径
                        const imgPath = d.imgPath || '/images/default.jpeg';
                        // 构建完整的图片URL
                        const imgUrl = `http://localhost:8080${imgPath}`;

                        // 返回包含图片元素的HTML字符串，添加了图片加载失败的处理
                        return `<img class="layui-upload-img layui-circle userFaceBtn userAvatar"
                        width=40 height=40 src="${imgUrl}" onerror="this.src='/images/default.jpeg'" />`;
                    }
                },
                {field: 'name', title: '姓名', align: 'center', width: '100'},
                {field: 'age', title: '年龄', align: 'center', width: '60'},
                {field: 'sex', title: '性别', align: 'center', width: '60',templet:function (d) {
                        return d.sex==1?'<span class="layui-badge layui-bg-blue">男</span>':'' +
                            '<span class="layui-badge layui-bg-orange">女</span>'
                }},
                {field: 'phone', title: '手机号', align: 'center', width: '130'},
                {field: 'idCard', title: '身份证', align: 'center', width: '180'},
                {field: 'address', title: '住址', align: 'center', width: '200'},
                {fixed: 'right', title: '操作', toolbar: '#userRowBar', align: 'center', width: '380'}
            ] ],
            done: function (data, curr, count) {
                //不是第一页时，如果当前返回的数据为0那么就返回上一页
                if (data.data.length == 0 && curr != 1) {
                    tableIns.reload({
                        page: {
                            curr: curr - 1
                        }
                    })
                }
            }
        });

        //监控模糊查询按钮事件
        form.on("submit(doSearch)", function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });

        //监控工具条事件 添加用户、批量删除
        table.on("toolbar(userTable)", function (obj) {
            switch (obj.event) {
                case 'add':
                    openAddLayer();
                    break;

                case 'batchDelete':
                    // 获取表格选中的数据
                    var checkStatus = table.checkStatus('userTable');
                    var selectedData = checkStatus.data;
                    if (selectedData.length === 0) {
                        layer.msg('请至少选择一行');
                    } else {
                        layer.confirm('真的要删除选中的 ' + selectedData.length + ' 条数据吗？', {
                            btn: ['删除', '取消']
                        }, function (index) {
                            // 发送批量删除请求
                            $.ajax({
                                url: '/user/batchDelete',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify(selectedData.map(item => item.id)),
                                success: function (res) {
                                    if (res.code === 200) {
                                        layer.msg('批量删除成功', {icon: 1});
                                        tableIns.reload(); // 刷新表格
                                    } else {
                                        layer.msg('批量删除失败：' + res.msg, {icon: 5});
                                    }
                                },
                                error: function (xhr, status, error) {
                                    layer.msg('网络请求失败，请重试', {icon: 5});
                                }
                            });
                        });
                    }
                    break;
            }
        });

        //监控行工具条事件
        table.on("tool(userTable)", function (obj) {
            //获取当前行数据
            var data = obj.data;
            switch (obj.event) {
                case 'delete':
                    deleteUser(data);
                    break;
                case 'update':
                    updateUser(data);
                    break;
                case 'resetPwd':
                    resetPwd(data);
                    break;
                case 'updateAvatar':
                    // 打开更换头像新窗口
                    openUpdateAvatar(data);
                    break;
                case 'selectRole':
                    selectRole(data);
                    break;
            }
        });

        var mainIndex;
        var url;

        //初始化所属学院、班级下拉列表函数
        function Initialize_DropdownList_ClassAndCollege() {
            // 初始化下拉列表【班级、学院】
            $.get("/user/listAllBanJi",function (res){
                var banji = res;   // 班级实体
                var dom_banji = $("#banji");
                var html = "<option value=''>选择班级</option>"
                $.each(banji, function (index, item){
                    html+="<option value='"+item.id+"'>"+item.name+"</option>";
                });
                dom_banji.html(html);
                form.render("select");
            })

            $.get("/user/listAllXueYuan",function (res){
                var xueyuan = res;   // 学院实体
                var dom_xueyuan = $("#xueyuan");
                var html = "<option value=''>选择学院</option>"
                $.each(xueyuan, function (index, item){
                    html+="<option value='"+item.id+"'>"+item.name+"</option>";
                });
                dom_xueyuan.html(html);
                form.render("select");
            })
        }

        //打开添加弹出层
        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['800px', '550px'],
                title: '添加用户',
                success: function () {
                    $("#dataFrm")[0].reset();

                    url = "/user/addUser";
                    //初始化排序码
                    // $.get("/user/loadUserMaxOrderNum", function (res) {
                    //     $("#ordernum").val(res.value);
                    // });

                    // 初始化下拉列表【班级、学院】
                    Initialize_DropdownList_ClassAndCollege();
                }
            });
        }

        //打开修改的弹出层
        function updateUser(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['800px', '550px'],
                title: '修改用户',
                success: function () {
                    //清空原有的数据
                    $("#dataFrm")[0].reset();
                    //装载新的数据
                    form.val("dataFrm", data);
                    url = "/user/updateUser";
                    // 初始化下拉列表【班级、学院】
                    Initialize_DropdownList_ClassAndCollege();
                }
            });
        }

        form.on("submit(doSubmit)", function (data) {
            $.post(url, data.field, function (res) {
                if (res.code == 200) {
                    tableIns.reload();
                }
                layer.msg(res.msg);
                layer.close(mainIndex);
            });
            return false;
        });

        //删除
        function deleteUser(data) {
            layer.confirm('你确定要删除【' + data.username + '】这个用户吗？', {icon: 3, title: '提示'}, function (index) {
                $.post("/user/deleteUser/" + data.id, function (res) {
                    if (res.code == 200) {
                        tableIns.reload();
                    }
                    layer.msg(res.msg);
                })
                layer.close(index);
            });
        }

        //重置密码
        function resetPwd(data) {
            layer.confirm('你确定要重置【' + data.username + '】这个用户的密码吗？', {icon: 3, title: '提示'}, function (index) {
                $.post("/user/resetPwd/" + data.id, function (res) {
                    if (res.code == 200) {
                        tableIns.reload();
                    }
                    layer.msg(res.msg);
                });
                layer.close(index);
            });
        }

        //监听用户名失去焦点事件
        $("#username").on("blur", function () {
            var username = $(this).val();
            $.get("/user/changeChineseToPinyin", {username: username}, function (res) {
                $("#loginname").val(res.value);
            })
        });

        //更换头像
        function openUpdateAvatar(data) {
            // 获取当前用户的头像路径
            const avatarPath = data.imgPath || '/images/default.jpeg';
            // 打开新窗口
            var uploadWindow = window.open(`/avatarUploadByUid?id=${data.id}&avatarPath=${encodeURIComponent(avatarPath)}`, '_blank', 'width=800,height=600');

            // 监听子窗口的消息
            window.addEventListener('message', function(e) {
                if (e.origin !== window.location.origin) return;

                if (e.data.type === 'avatarUpdate') {
                    // 更新头像显示
                    $('#userFace').attr('src', e.data.path);
                    $('#imgPath').val(e.data.path);
                    tableIns.reload();  // 刷新表格更新头像
                    layer.msg('头像更新成功');
                }
            });
        }

        //打开分配角色的弹出层
        function selectRole(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#selectUserRoleDiv"),
                area: ['650px', '400px'],
                title: '给' + data.username + '分配角色',
                btn: ['<span class=layui-icon>&#xe605;确认分配</span>', '<span class=layui-icon>&#x1006;取消分配</span>'],
                btnAlign: 'c',
                yes: function (index, layero) {
                    var checkStatus = table.checkStatus('roleTable');
                    var params = "uid=" + data.id;
                    $.each(checkStatus.data, function (index, item) {
                        params += "&ids=" + item.id;
                    });
                    $.post("/user/saveUserRole", params, function (res) {
                        layer.msg(res.msg);
                        layer.close(mainIndex);
                    })
                },
                btn2: function (index, layero) {
                    //关闭弹出层
                },
                success: function () {
                    initRoleTable(data);
                }
            });
        }

        var roleTableIns;

        //初始化角色列表
        function initRoleTable(data) {
            console.log(data);
            roleTableIns = table.render({
                elem: '#roleTable',
                url: '/user/initRoleByUserId',
                //将用户id传到后台去
                where: {
                    id: data.id
                },
                cols: [ [
                    {type: 'checkbox', align: 'center'},
                    {field: 'id', title: 'ID', align: 'center'},
                    {field: 'name', title: '角色名称', align: 'center'},
                    {field: 'remark', title: '角色备注', align: 'center'}
                ] ]
            });
        }
    });
</script>

</body>
</html>